// -----------------------------------------------------------------------
//  <copyright file="Extensions.cs" company="LiuliuSoft">
//      Copyright (c) 2022-2025 DaprPlus. All rights reserved.
//  </copyright>
//  <site>https://www.dapr.plus</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2025-02-13 21:02</last-date>
// -----------------------------------------------------------------------

using OpenIddict.Validation.AspNetCore;


namespace DaprPlus.Authorization.OpenIddict;

public static class Extensions
{
    public static IServiceCollection AddOpenIddictValidation(this IServiceCollection services)
    {
        services.AddAuthentication(OpenIddictValidationAspNetCoreDefaults.AuthenticationScheme);

        services.Configure<OpenIddictValidationOptions>(sectionName: OpenIddictValidationOptions.Position);
        var options = services.GetOptions<OpenIddictValidationOptions>(OpenIddictValidationOptions.Position);
        if (options.Authority.IsNullOrEmpty())
        {
            return services;
        }
        services.AddOpenIddict()
            .AddValidation(opts =>
            {
                opts.SetIssuer(options.Authority);
                opts.AddAudiences(options.Audiences);

                if (!options.IntrospectionClientId.IsNullOrEmpty() && !options.IntrospectionClientSecret.IsNullOrEmpty())
                {
                    opts.UseIntrospection()
                        .SetClientId(options.IntrospectionClientId!)
                        .SetClientSecret(options.IntrospectionClientSecret!);
                }

                opts.UseSystemNetHttp();
                opts.UseAspNetCore();
            });

        return services;
    }
}
